package com.atguigu.tingshu.dispatch.job;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.tingshu.model.dispatch.XxlJobLog;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserJobHandler {

    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @XxlJob("userUpdateExpiredVipStatus")
    public void updateExpiredVipStatus(){
        // 任务执行的初始时间
        long startTime = System.currentTimeMillis();
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        log.info("更新已过期vip用户的状态，定时任务开始！");
        try {
            // 执行定时任务更新已过期vip用户的状态
            Result result = this.userInfoFeignClient.updateExpiredVipStatus();
            if (result == null){
                xxlJobLog.setStatus(0);
                xxlJobLog.setError("更新已过期vip用户状态时，调用远程接口失败！");
                XxlJobHelper.handleFail();
            } else {
                xxlJobLog.setStatus(1);
                XxlJobHelper.handleSuccess();
            }
        } catch (Exception e) {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError("未知错误：" + e.getMessage());
            XxlJobHelper.handleFail();
        } finally {
            // 任务的执行时间
            xxlJobLog.setTimes((int)(System.currentTimeMillis() - startTime));
            this.xxlJobLogMapper.insert(xxlJobLog);
            log.info("更新已过期vip用户的状态，定时任务执行结束！");
        }
    }
}
